#include <stdio.h>
#define usedlen 30
int resolve(int *used, int words[usedlen][3], char lstc, int n, int tmp, int *ans, int *anslen);
int main()
{
    int tmp, tmp1, words[usedlen][3], ans[100] = {0}, anslen[1] = {0};
    int n;
    int lstc;
    int used[usedlen] = {0};
    scanf("%d", &n);
    getchar();
    for (int i = 0; i < n; i++)
    {
        tmp = words[i][0] = getchar();
        for (int j = 1; 1; j++)
        {
            tmp = getchar();

            if ('\n' == tmp)
            {
                words[i][1] = j;
                words[i][2] = tmp1;
                break;
            }
            tmp1 = tmp;
        }
    }
    lstc = getchar();
    for (int i = 0; i < n; i++)
    {
        if (words[i][0] == lstc)
            resolve(used, words, lstc, n, words[i][2], ans, anslen);
    } // 需要判断
    for (int i = 0; i < n; i++)
    {
        printf("%d ", ans[i]);
    }
}
int resolve(int *used, int words[usedlen][3], char lstc, int n, int tmpp, int *ans, int *anslen)
{
    int used1[usedlen] = {0};
    _Bool islast = 1;
    for (int i = 0; i < n; i++)
    {
        used1[i] = used[i];
    }
    for(int i=0;i<n;i++){
        printf("%d",used1[i]);
    }printf("\n");
    for (int i = 0; i < n; i++)
    {
        if (words[i][0] == lstc && used1[i] < 2)
        {

            used1[i]++;
            resolve(used1, words, words[i][3], n, words[i][2], ans, anslen);
            used1[i]--;
            islast = 0;
        }
    }
    if (islast)
    {

        int tmp2 = tmpp;
        for (int i = 0; i < n; i++)
        {
            tmp2 += used1[i] * words[i][2];
        }
        ans[anslen[0]++] = tmp2;
    }
}